package core

import (
	"time"
	"strconv"
	"bytes"
	"crypto/sha256"
)

type Block struct {
	Timestamp int64 //区块创建的时间戳
	Data []byte//区块包含的数据
	PrevBlockHash []byte//前一个区块的哈希值
	Hash	[]byte//区块自身的哈希值，用于校验区块数据的有效性
	Nonce int

}
//创建一个区块
func NewBlock(data string,preBlockHash []byte) *Block{
	block:=&Block{time.Now().Unix(),[]byte(data),preBlockHash,[]byte{},0}

	pow:=NewProofofwork(block)
	nonce,hash:=pow.Run()
	block.Hash=hash[:]
	block.Nonce=nonce
	return block
}


//设置哈希值
func (b *Block) SetHash(){
	timestamp:=[]byte(strconv.FormatInt(b.Timestamp,10))
	headers:=bytes.Join([][]byte{b.PrevBlockHash,b.Data,timestamp},[]byte{})
	hash:=sha256.Sum256(headers)
	b.Hash=hash[:]
}

func NewGenesisBlock()*Block{
	return NewBlock("genesis block",[]byte{})
}